package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Measurement;
import model.Roll;
import model.Sensor;
import model.User;
import DAO.MeasurementsDao;
import DAO.RollDao;
import DAO.SensorDao;
import DAO.UserDao;
import database.DBManager;

/**
 * Servlet implementation class UserServlet
 */
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private DBManager myDb;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init( ServletConfig servletconfig ) {
		// Initialisatie
		myDb = ( DBManager ) servletconfig.getServletContext().getAttribute( "dbmanager" );
	}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher view = null;
		if(!isLoggedIn(request)){
			view = request.getRequestDispatcher("index.jsp");
		}else if(!gotAuth(request)){
			view = request.getRequestDispatcher("SensorServlet?page=home");
		}else{
			Logger.createLog(request);
			UserDao ud = new UserDao(myDb);
			RollDao rd = new RollDao(myDb);
			String[] url = request.getQueryString().split( "=" );
			if( url[0].equals("page") && url[1].equals("user")) {
				if(!isLoggedIn(request)){
					view = request.getRequestDispatcher("index.jsp");
				}else{
					ArrayList<User> users = ud.getUsers();
					ArrayList<Roll> rolls = rd.getRolls();
					request.setAttribute("users", users);
					request.setAttribute("rolls", rolls);
					view = request.getRequestDispatcher( "/WEB-INF/users.jsp" );
				}
			}else if(url[0].equals("page") && url[1].equals("logout")){
				unsetSession(request);
				view = request.getRequestDispatcher("index.jsp");
			}else if(url[0].equals("page") && url[1].equals("add")){
				if(!isLoggedIn(request)){
					view = request.getRequestDispatcher("index.jsp");
				}else{
					ArrayList<User> users = ud.getUsers();
					request.setAttribute("users", users);
					request.setAttribute("rolls", rd.getRolls());
					request.setAttribute("toAdd", "true");
					view = request.getRequestDispatcher("WEB-INF/users.jsp");
				}
			}else if(url[0].equals("delete")){
				ud.deleteUser(Integer.parseInt(url[1]));
				request.setAttribute("url", "UserServlet?page=user");
				view = request.getRequestDispatcher( "/WEB-INF/redirect.jsp" );
			}else if(url[0].equals("page") && url[1].equals("login")){
				view = request.getRequestDispatcher( "WEB-INF/login.jsp" );
			}else{
				view = request.getRequestDispatcher( "index.jsp" );
			}
			request = getWarningInfo(request);
		}
		view.forward( request, response );
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher view = null;
		String[] url = request.getQueryString().split( "=" );
		if(!isLoggedIn(request)){
			view = request.getRequestDispatcher("index.jsp");
		}
		
		if(url[0].equals("page") && url[1].equals("login")){
			UserDao udao = new UserDao(myDb);
			User user = udao.userLogin(request.getParameter("gebruikersnaam"), request.getParameter("wachtwoord"));
			
			//int klantnummer = 0;
			String gebruikersnaam = request.getParameter("gebruikersnaam");
			String wachtwoord = request.getParameter("wachtwoord");
			if(gebruikersnaam.equals("") || wachtwoord.equals("")){
				request.setAttribute( "succeeded", "Inloggegevens zijn niet ingevuld");
				view = request.getRequestDispatcher("index.jsp");
			}else{
				if(user == null){
					request.setAttribute( "succeeded", "Verkeerde inloggegevens");
					view = request.getRequestDispatcher("index.jsp");
				}else{
					setSession(request, user);
					request.setAttribute("url", "SensorServlet?page=home");
					view = request.getRequestDispatcher( "/WEB-INF/redirect.jsp" );
				}
			}
		} else {
			if (!gotAuth(request)) {
				view = request.getRequestDispatcher("SensorServlet?page=home");
				System.out.println("GEEN AUTH");
			} else {
				if (url[0].equals("page") && url[1].equals("added")) {
					// voeg gebruiker toe
					addKlant(request);
					request.setAttribute("url", "UserServlet?page=user");
					view = request.getRequestDispatcher("/WEB-INF/redirect.jsp");
				}else if(url[0].equals("page") && url[1].equals("username")){
					request.setAttribute("warning", "Ongeldige gebruikersnaam. Deze gebruikersnaam is al bekend");
					view = request.getRequestDispatcher("WEB-INF/users.jsp");
				}else {
					view = request.getRequestDispatcher("UserServlet?page=user");
				}
				request = getWarningInfo(request);
			}
		}
		view.forward( request, response );
	}
	
	private boolean isLoggedIn(HttpServletRequest request){
		HttpSession session = request.getSession();
		boolean loggedIn = false;
		if(session.getAttribute("logged") != null){
			if(session.getAttribute("logged").equals("true")){
				loggedIn = true;
			}
		}
		return loggedIn;
	}
	
	private boolean gotAuth(HttpServletRequest request){
		HttpSession session = request.getSession();
		boolean gotAuth = false;
		if(session.getAttribute( "rollID" ) != null){
			int rollId = (Integer) session.getAttribute("rollID");
			if(rollId == 1){
				gotAuth = true;
			}
		}
		return gotAuth;
	}
	
	private boolean addKlant(HttpServletRequest request){
		boolean succeeded = false;
		if(request.getParameter("wachtwoord").equals(request.getParameter("wachtwoord2"))){
			UserDao udao = new UserDao(myDb);
			String gebruikersnaam = request.getParameter("gebruikersnaam");
			if(udao.uniqueUsername(gebruikersnaam)){
				int roll = Integer.parseInt(request.getParameter("rolls"));
				udao.createKlant(gebruikersnaam, request.getParameter("wachtwoord"), roll);
				succeeded = true;
			}
		}
		return succeeded;
	}

	private void setSession( HttpServletRequest request, User user){
		HttpSession session = request.getSession();
		session.setAttribute( "klantnummer", user.getUserID());
		session.setAttribute( "gebruikersnaam", user.getUsername());
		session.setAttribute( "rollID", user.getRolID());
		session.setAttribute( "logged", "true" );
		session.setAttribute("recording", "false");
		Cookie cookie = new Cookie( "JSESSIONID", session.getId() );
		cookie.setMaxAge( 60 * 60 * 24 * 7 );
	}
	
	private void unsetSession(HttpServletRequest request){
		HttpSession session = request.getSession();
		session.setAttribute( "logged", "false" );
		session.setAttribute( "gebruikersnaam", "" );
		session.setAttribute( "klantnummer", 0 );
		Cookie cookie = new Cookie( "JSESSIONID", session.getId() );
		cookie.setMaxAge( -1 );
	}
	
	private HttpServletRequest getWarningInfo(HttpServletRequest request){
		MeasurementsDao md = new MeasurementsDao(myDb);
		ArrayList<Measurement> latestMeasurements = new ArrayList<Measurement>();
		for(int i = 1; i <= 5; i++){
			Measurement measurement = md.getLatestMeasurementByID(i);
			if(measurement != null){
				latestMeasurements.add(measurement);
			}
		}
		SensorDao sdao = new SensorDao(myDb);
		ArrayList<Sensor> sensors = sdao.getSensors();
		request.setAttribute("sensorsmax", sensors);
		request.setAttribute("latestMeasurements", latestMeasurements);
		return request;
	}
}
